#!/bin/bash

if [ -f "/install_extensions.sh" ]; then
    bash /install_extensions.sh
    rm /install_extensions.sh
fi

if [ -f "/install_conda_packages.sh" ]; then
	bash /install_conda_packages.sh
    rm /install_conda_packages.sh
fi

# 判断B用户是否存在
if id "${USER_NAME}" >/dev/null 2>&1; then
    echo "${USER_NAME} user already exists."
else
    # 创建用户
    groupadd -g ${PGID} ${GROUP_NAME}
    useradd -m -s /bin/bash -d /home/${USER_NAME} -u ${PUID} -g ${PGID} ${USER_NAME}

    chown -R ${USER_NAME}:${GROUP_NAME} /home/${USER_NAME}
	chown -R ${USER_NAME}:${GROUP_NAME} /config/
	echo 'export RUSTUP_HOME="/home/${USER_NAME}/.rustup"' >> /home/${USER_NAME}/.bashrc
	echo 'export CARGO_HOME="/home/${USER_NAME}/.cargo"' >> /home/${USER_NAME}/.bashrc

    # 赋予B用户权限
    echo "${USER_NAME} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
	chown -R ${USER_NAME}:${GROUP_NAME} /volume

	su - ${USER_NAME} -c "/opt/anaconda3/bin/conda config --add envs_dirs /config/conda/envs"
	mkdir -p /home/${USER_NAME}/.pip
	chown -R ${USER_NAME}:${GROUP_NAME} /opt/anaconda3 /config/conda/ /home/${USER_NAME}/.pip

	#ssh config
	mkdir /home/${USER_NAME}/.ssh
    chmod 700 /home/${USER_NAME}/.ssh
	echo  ${USER_PUB_KEY}  >> /home/${USER_NAME}/.ssh/authorized_keys 
    chmod 600 /home/${USER_NAME}/.ssh/authorized_keys
	chown -R ${USER_NAME}:${GROUP_NAME} /home/${USER_NAME}/.ssh

	#共享vscode 扩展
	mkdir -p /home/${USER_NAME}/.vscode-server/
	ln -s /config/extensions /home/${USER_NAME}/.vscode-server/	
	chown -R ${USER_NAME}:${GROUP_NAME} /home/${USER_NAME}/.vscode-server

	#docker
	usermod -aG docker ${USER_NAME}
	chmod 666 /var/run/docker.sock
fi

#echo "CODE_AUTH ${CODE_AUTH} "
# 切换到B用户
/etc/init.d/ssh restart
su - ${USER_NAME} -c "/app/bin/code-server --disable-telemetry --bind-addr 0.0.0.0:8080 --config /config/config.yaml --auth ${CODE_AUTH} --user-data-dir /config/data --extensions-dir /config/extensions ${CODE_ARGS} /volume/workspace"